package service.jun.com.myservicedemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {
    public Intent mIntent;
    MyService myService;
    boolean isBound=false;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        findViewById (R.id.btnStratService).setOnClickListener (this);
        findViewById (R.id.btnstopService).setOnClickListener (this);
        findViewById (R.id.btnBindService).setOnClickListener (this);
        findViewById (R.id.btnUnBindService).setOnClickListener (this);
        findViewById (R.id.btnGetRandom).setOnClickListener (this);
        mIntent=new Intent (MainActivity.this,MyService.class);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId ()) {
            case R.id.btnStratService:
                startService (mIntent);
                break;
            case R.id.btnstopService:
                stopService (mIntent);
                break;
            case R.id.btnBindService:
                bindService (mIntent,this, Context.BIND_AUTO_CREATE);
                break;
            case R.id.btnUnBindService:
                unbindService (this);
                break;
            case R.id.btnGetRandom:
                getRandom();
                break;
        }
    }

    private void getRandom() {
        Log.e (TAG, "isBound =="+isBound);
        if(isBound){
            Toast.makeText (MainActivity.this, myService.getRandom ()+"", Toast.LENGTH_SHORT).show ();
        }
    }


    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.e (TAG, "onServiceConnected: " );
        MyService.LocalBinder mbinder= (MyService.LocalBinder) service;
        myService=mbinder.getService ();
        isBound=true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.e (TAG, "onServiceDisconnected: " );
        isBound=false;
    }


}
